<script setup lang="ts">
import { useLoading } from "@/hooks";
import { addUser, updateUser } from "@/service/api/user";
type FormModel = Pick<
  CommonList.UserList,
  "nickName" | "userName" | "status" | "phonenumber" | "password"
>;
const props = withDefaults(defineProps<Props>(), {
  type: "add",
  modalData: null,
});
const emit = defineEmits<Emits>();
const formRef = ref();
const defaultFormModal: FormModel = {
  nickName: "",
  userName: "",
  status: "0",
  phonenumber: undefined,
  password: "",
};
const formModel = ref({ ...defaultFormModal });
const { loading: submitLoading, startLoading, endLoading } = useLoading(false);
const rules = computed(() => {
  return {
    userName: {
      required: true,
      trigger: "blur",
      message: "请输入用户名",
    },
    nickName: {
      required: true,
      trigger: "blur",
      message: "请输入昵称",
    },
    password: {
      required: true,
      trigger: "blur",
      message: "请输入密码",
    },
  };
});
interface Props {
  visible: boolean;
  type?: ModalType;
  modalData?: any;
}
interface Emits {
  (e: "update:visible", visible: boolean): void;
  (e: "refresh"): void;
}

const modalVisible = computed({
  get() {
    return props.visible;
  },
  set(visible) {
    closeModal(visible);
  },
});
function closeModal(visible = false) {
  emit("update:visible", visible);
}
type ModalType = "add" | "edit";
const title = computed(() => {
  const titles: Record<ModalType, string> = {
    add: "添加用户",
    edit: "编辑用户",
  };
  return titles[props.type];
});

function UpdateFormModelByModalType() {
  const handlers = {
    add: () => {
      formModel.value = { ...defaultFormModal };
    },
    edit: () => {
      if (props.modalData) formModel.value = { ...props.modalData };
    },
  };
  handlers[props.type]();
}
watch(
  () => props.visible,
  (newValue) => {
    if (newValue) UpdateFormModelByModalType();
  }
);

/** 添加/编辑 */
async function submitModal() {
  const handlers = {
    async add() {
      return new Promise((resolve) => {
        addUser(formModel.value).then(() => {
          window.$message.success("新增成功");
          resolve(true);
          emit("refresh");
        }).finally(()=>{
          endLoading()
        })
      });
    },
    async edit() {
      return new Promise((resolve) => {
        updateUser(formModel.value).then(() => {
          window.$message.success("编辑成功");
          resolve(true);
          emit("refresh");
        }).finally(()=>{
          endLoading()
        })
      });
    },
  };
  await formRef.value?.validate();
  startLoading();
  (await handlers[props.type]()) && closeModal();
}
</script>

<template>
  <n-modal
    v-model:show="modalVisible"
    :mask-closable="false"
    preset="card"
    :title="title"
    class="w-700px"
    :segmented="{
      content: true,
      action: true,
    }"
  >
    <n-form
      label-placement="left"
      :model="formModel"
      label-align="left"
      :label-width="80"
      :rules="rules"
      ref="formRef"
    >
      <n-grid :cols="24" :x-gap="18">
        <n-form-item-grid-item :span="12" label="用户名" path="userName">
          <n-input v-model:value="formModel.userName" />
        </n-form-item-grid-item>
        <n-form-item-grid-item
          :span="12"
          label="密码"
          path="password"
          v-if="props.type !== 'edit'"
        >
          <n-input
            v-model:value="formModel.password"
            type="password"
            show-password-on="mousedown"
          />
        </n-form-item-grid-item>
        <n-form-item-grid-item :span="12" label="昵称" path="nickName">
          <n-input v-model:value="formModel.nickName" />
        </n-form-item-grid-item>
        <n-form-item-grid-item :span="12" label="手机号码" path="phonenumber">
          <n-input v-model:value="formModel.phonenumber" :input-props="{ type: 'tel' }" />
        </n-form-item-grid-item>
        <n-form-item-grid-item :span="12" label="状态" path="status">
          <n-switch
            v-model:value="formModel.status"
            checked-value="0"
            unchecked-value="1"
          >
            <template #checked> 启用 </template>
            <template #unchecked> 禁用 </template>
          </n-switch>
        </n-form-item-grid-item>
      </n-grid>
    </n-form>
    <template #action>
      <n-space justify="center">
        <n-button @click="closeModal()"> 取消 </n-button>
        <n-button type="primary" :loading="submitLoading" @click="submitModal">
          提交
        </n-button>
      </n-space>
    </template>
  </n-modal>
</template>

<style scoped></style>
